<template>
    <div style="border: 1px solid #ccc">
        <el-input v-bind="$attrs" v-model="title" placeholder="请输入标题"></el-input>
        <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
        />
        <Editor
            style="height: 80vh; overflow-y: hidden;"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
        />
    </div>
    <el-button @click="submitNew()">提交</el-button>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, reactive} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import request from "@/util/request.js";
import aes from "@/util/aes.js";
import {useRouter} from 'vue-router'
import {Boot} from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
import {ElMessageBox} from "element-plus";

export default {
    components: { Editor, Toolbar },
    setup() {
        // 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
        Boot.registerModule(attachmentModule)

        let notices = reactive({})
        const title = ref('')
        const router = useRouter()
        if (router.currentRoute.value.query.id !== undefined) {
            notices.id = router.currentRoute.value.query.id
            getContent(router.currentRoute.value.query.id)
        }

        // 编辑器实例，必须用 shallowRef
        const editorRef = shallowRef()

        const editorConfig = {                       // JS 语法
            MENU_CONF: {},
            placeholder: '请输入内容...',
            attachment: {
                menuKeys: ['downloadAttachment'], // “下载附件”菜单
            },
        }
        const toolbarConfig = {
            insertKeys: {
                index: 10, // 自定义插入的位置
                keys: ['uploadAttachment'], // “上传附件”菜单
            },
        }
        editorConfig.MENU_CONF['uploadAttachment'] = {
            // “上传附件”菜单的配置
            server: '/api/related_notice/uploadFile', // 服务端地址
            timeout: 5 * 1000, // 5s
            headers: {
                "account": JSON.parse(localStorage.getItem('user')).accountNo,
                "token": JSON.parse(localStorage.getItem('user')).token
            },
            fieldName: 'file',
            maxFileSize: 10 * 1024 * 1024, // 10M
            // 插入附件到编辑器
            // // 用户自定义上传

            // // 上传成功后，用户自定义插入文件
            customInsert(res, file, insertFn) {
                res = aes.decrypt(res)

                // 插入附件到编辑器
                insertFn(`customInsert-${file.name}`, res.data)
                return "ok"
            },

            // // 上传成功后，用户自定义插入文件
            // customUpload(res, insertFn) {
            //   res = aes.decrypt(res)
            //   const { url } = res.data || {}
            //   // 插入附件到编辑器
            //   insertFn(res.data, url)
            // },
        }
        // 这里虽然用到了post请求，但是前端没进行加密。所以后端也没必要解密，，只要将后端返回的数据进行解密即可
        editorConfig.MENU_CONF['uploadImage'] = {
            server: '/api/related_notice/uploadSign',
            fieldName: "file",
            headers: {
                "account" : JSON.parse(localStorage.getItem('user')).accountNo,
                "token" : JSON.parse(localStorage.getItem('user')).token
            },
            customInsert(res, insertFn) {
                res = aes.decrypt(res)
                // JS 语法
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(res.data)
            },
        }
        editorConfig.MENU_CONF['uploadVideo'] = {
            server: '/api/related_notice/uploadSign',
            fieldName: "file",
            headers: {
                "account" : JSON.parse(localStorage.getItem('user')).accountNo,
                "token" : JSON.parse(localStorage.getItem('user')).token
            },
            customInsert(res, insertFn) {
                res = aes.decrypt(res)
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(res.data)
            },
        }

        // 内容 HTML
        const valueHtml = ref('<p>hello</p>')

        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            const editor = editorRef.value
            if (editor == null) return
            editor.destroy()
        })

        const handleCreated = (editor) => {
            editorRef.value = editor // 记录 editor 实例，重要！
        }
        function submitNew() {
          let wxNotice = {
            accountNo: JSON.parse(localStorage.getItem('user')).accountNo,
            noticeType: title.value,
            level: "紧急"
          }
            notices.title=title.value
            notices.content=valueHtml.value
            notices.editor = JSON.parse(localStorage.getItem('user')).accountNo
          request.post("/related_notice/edit", notices).then(() => {
            ElMessageBox.alert("通知发送成功，是否微信提醒", {
              title: '发送成功',
              showCancelButton: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            }).then(() => {
              request.post("/wx_push_notice/push_message", wxNotice).then(res => {
                if (res.data.code === '200') {
                  ElMessageBox.alert("微信已发送通知", {
                    title: '发送成功',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                  }).then(() => {
                    // 刷新页面
                    window.location.reload();
                  })
                }
              })
            });
          })
        }

      function truncateContent(content) {
        if (!content) return ''; // 如果描述为空，返回空字符串
        // 清除 HTML 标签
        const withoutTags = content.replace(/(<([^>]+)>)/gi, "");
        // 截取前20个字符
        if (withoutTags.length > 40) {
          return withoutTags.slice(0, 40) + '...';
        }
        return withoutTags;
      }
        function getContent(id) {
            request.get("/related_notice/getById?id=" + id).then(res => {
                title.value = res.data.data.title
                valueHtml.value = res.data.data.content
            })
        }

        return {
            editorRef,
            valueHtml,
            mode: 'default', // 或 'simple'
            editorConfig,
            toolbarConfig,
            handleCreated,
            submitNew,
            title
        };
    }
}
</script>
